﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Uniblocks;
using UnityEngine;

public class DataUtl : MonoBehaviour
{
    public static ushort GetBlockId(float h)
    {
        if (h == -64)
        {
            return 10;
        }
        List<BlockData> list = new List<BlockData>();
        foreach (var item in DataManager.instance.blockDic)
        {
            if (item.Value.chance == 0) continue;
            if (h >= item.Value.findY - item.Value.range && h <= item.Value.findY + item.Value.range)
            {
                int ch = 0;
                if (h >= item.Value.findY)
                {
                    ch = (int)Mathf.Lerp(item.Value.chance, 0, (h - item.Value.findY) / item.Value.range);
                }
                else
                {
                    ch = (int)Mathf.Lerp(item.Value.chance, 0, (item.Value.findY - h) / item.Value.range);
                }
                list.Add(new BlockData() { chance = ch, id = item.Key });
            }
        }
        list.Sort((x, y) => { return x.chance - y.chance; });
        int totalChance = list.Sum(a => a.chance);
        int rand = Random.Range(0, totalChance);
        int t = 0;
        foreach (var item in list)
        {
            t += item.chance;
            if (t > rand)
            {
                return item.id;
            }
        }
        return 1;
    }
}
